﻿using Domain;
using Domain.Event;
using MediatR;

namespace WebAPI.Event
{
    /// <summary>
    /// 处理监听的事件- 记录登录的操作日志
    /// </summary>
    public class UserAccessResultEventHandle : INotificationHandler<UserAccessResultEvent>
    {
        private readonly IUserDomainRepository repository;

        public UserAccessResultEventHandle(IUserDomainRepository repository)
        {
            this.repository = repository;
        }

        /// <summary>
        /// 记录登录的操作日志
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task Handle(UserAccessResultEvent notification, CancellationToken cancellationToken)
        {
            string msg;
            switch (notification.Result) 
            {
                case Domain.UserAccessResult.OK:
                    msg = $"{notification.PhoneNumber}登陆成功";
                    break;
                case Domain.UserAccessResult.PhoneNumberNotFound:
                    msg = $"{notification.PhoneNumber}登陆失败，因为用户不存在";
                    break;
                case Domain.UserAccessResult.PasswordError:
                    msg = $"{notification.PhoneNumber}登陆失败，密码错误";
                    break;
                case Domain.UserAccessResult.NoPassword:
                    msg = $"{notification.PhoneNumber}登陆失败，没有设置密码";
                    break;
                case Domain.UserAccessResult.Lockout:
                    msg = $"{notification.PhoneNumber}登陆失败，被锁定";
                    break;
                default:
                    throw new NotImplementedException();
            }
            //return Task.CompletedTask;
            await repository.AddNewLoginHistoryAsync(notification.PhoneNumber, msg);
        }
    }
}
